//
//  RecordVideoController.swift
//  微信小视频
//
//  Created by 罗杰 on 2016/11/13.
//  Copyright © 2016年 罗杰. All rights reserved.
//
let document = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
protocol RecordVideoControllerDelegate {
    func controller(controller:RecordVideoController, recordFinished url:URL)
}

import UIKit
import AVFoundation
class RecordVideoController: UIViewController , AVCaptureFileOutputRecordingDelegate{
    var delegate: RecordVideoControllerDelegate?
    var outputFilePath: URL?
    private let session = { () -> AVCaptureSession in 
       let sess = AVCaptureSession()
        if sess.canSetSessionPreset(AVCaptureSessionPresetMedium) {
          sess.sessionPreset = AVCaptureSessionPresetMedium
        }
         return sess
    }()
    private let output = AVCaptureMovieFileOutput()
    
    @IBAction func dissmissClick(_ sender: AnyObject) {
        self.delegate?.controller(controller: self, recordFinished: self.outputFilePath!)
        self.dismiss(animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do {
            session.beginConfiguration()
            let input = try AVCaptureDeviceInput(device: device)
            if self.session.canAddInput(input) {
                session.addInput(input)
            }
            if session.canAddOutput(output) {
               session.addOutput(output)
            }
            let audioDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio)
            let audioInput = try? AVCaptureDeviceInput(device: audioDevice)
            if session.canAddInput(audioInput) {
                session.addInput(audioInput);
            }
            session.commitConfiguration()
            let previewLayer = AVCaptureVideoPreviewLayer(session: session)
            previewLayer?.backgroundColor=UIColor.brown.cgColor
            previewLayer?.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height:  UIScreen.main.bounds.size.width)
            previewLayer?.videoGravity=AVLayerVideoGravityResizeAspectFill
            self.view.layer.addSublayer(previewLayer!)
            
            self.session.startRunning()
        } catch let error as NSError {
            print(error)
        }
        
        
        
        
        
        // Do any additional setup after loading the view.
    }

    func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
        if error == nil {
            let ret:Bool = FileManager.default.fileExists(atPath: outputFileURL.absoluteString)
           print(outputFileURL,ret)
            UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.absoluteString, nil, nil, nil)
        }
    }
    func capture(_ captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAt fileURL: URL!, fromConnections connections: [Any]!){
     print("kkkkkkkssss\(fileURL)   \(connections)")
    
    }
   @IBAction func recordAction(_ sender: AnyObject) {
        let longGesture : UILongPressGestureRecognizer = sender as! UILongPressGestureRecognizer
        let url = URL(fileURLWithPath: (document! as NSString).appendingPathComponent("ddjk78dhjg6hjdmmm.mp4"))
        self.outputFilePath=url
        switch longGesture.state {
        case .began:
            if session.isRunning == false {
                self.session.startRunning()
            }
            self.output.startRecording(toOutputFileURL:url, recordingDelegate: self)
            print("开始")
           
        case .ended:
            self.output.stopRecording()
            self.session.stopRunning()
            
            print("停止")
        default: break
//            self.session.stopRunning()
            
        }
        
        
        
        
        
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
